import $config from '@/config/index.config.js';
const upload = async (type) => {
	let baseUrl = $config.baseUrl // baseUrl需要引入，可以在封装的请求方法中获取
	return new Promise((resolve, reject) => {
		uni.chooseImage({
			count: 1,
			sizeType: ['original'],
			sourceType: ['album', 'camera'],
			success: res => {
				uni.uploadFile({
					url: baseUrl + '/system/basic/uploadImage', 
					filePath: res.tempFilePaths[0],
					name: 'img',
					/* formData: {
						type: type
					}, */
					header: {
						Authorization: uni.getStorageSync("hhToken")
					},
					success: r => {
						let imgData = JSON.parse(r.data)
						imgData.showImg = res.tempFilePaths[0]
						resolve(imgData)
					},
					fail: (r) => {
						
					}
				});
			}
		})
	})
}


// 调用方式：
// 1、在min.js中引入工具类import tool from '@/tool/tool'
// 2、在min.js中注册：Vue.prototype.$upload = tool.upload
// 3、页面调用：this.$upload().then(res => {
//              res为上传接口返回数据
//            })
//统一提示方便全局修改
const msg = (title, duration = 1500, mask = false, icon = 'none') => {
	if (Boolean(title) === false) {
		return;
	}
	uni.showToast({
		title,
		duration,
		mask,
		icon
	});
}
// 获取地址栏中某个key的值，如果没有key，返回false
const getQueryVariable = (key, url) => {
	/* if (url.indexOf('?') >= 0) {
	  var query = url.split('?')[1];
	  var vars = query.split("&");
	  for (var i = 0; i < vars.length; i++) {
	    var pair = vars[i].split("=");
	    if (pair[0] == key) {
	      return pair[1];
	    }
	  }
	}
	
	return (false); */
	var query = url.split('?');
	var qq = "";
	query.forEach((item, index) => {
		if (item.indexOf("ref=") > -1) {
			qq = item;
		}
	})
	//console.log(qq);
	var vars = qq.split("&");
	//console.log(vars)
	for (var i = 0; i < vars.length; i++) {
		var pair = vars[i].split("=");
		if (pair[0] == key) {
			return pair[1];
		}
	}
	return (false);
}
// 对象转get拼接参数
const objParseParam = (obj) => {
	let paramsStr = '';
	if (obj instanceof Array) return paramsStr;
	if (!(obj instanceof Object)) return paramsStr;
	for (let key in obj) {
		paramsStr += `${key}=${obj[key]}&`;
	}
	return paramsStr.substring(0, paramsStr.length - 1);
}
// 复制--兼容app-h5
const copy = (val) => {
	// #ifdef APP-PLUS
	uni.setClipboardData({
		data: val,
		success() {
			msg('复制成功！')
		},
		fail() {
			msg('复制失败！')
		}
	})
	// #endif
	// #ifdef H5
	msg(h5Copy(val));
	// #endif
}
// H5复制
const h5Copy = (content) => {
	let textarea = document.createElement('textarea');
	textarea.value = content;
	textarea.readOnly = 'readOnly';
	document.body.appendChild(textarea);
	textarea.select(); // 选择对象
	textarea.setSelectionRange(0, content.length); //核心
	let result = document.execCommand('Copy'); // 执行浏览器复制命令
	textarea.remove();
	const msgs = result ? '复制成功' : '复制失败';
	msg(msgs);
}
// 异步获取设备信息
const getInfoAsync = () => {
	return new Promise((resolve, reject) => {
		plus.device.getInfo({
			success(e) {
				resolve(e);
			},
			fail(e) {
				reject(e.message);
			}
		});
	});
}
const openLocation = (latitude, longitude, name, address) => {
	uni.openLocation({
		latitude: latitude,
		longitude: longitude,
		name: name,
		address: address,
		fail(e) {
			msg('地图调用失败，请重试，或者反馈问题！')
		}
	})
}
// 生成随机数
const random = (min, max) => {
	switch (arguments.length) {
		case 1:
			return parseInt(Math.random() * min + 1, 10);
			break;
		case 2:
			return parseInt(Math.random() * (max - min + 1) + min, 10);
			break;
		default:
			return 0;
			break;
	}
}
// 浏览器地址栏参数转对象
const getRequestParameters = (locationhref) => {
	let href = locationhref || '';
	let theRequest = new Object();
	let str = href.split('?')[1];
	if (str != undefined) {
		let strs = str.split('&');
		for (let i = 0; i < strs.length; i++) {
			theRequest[strs[i].split('=')[0]] = strs[i].split('=')[1];
		}
	}
	return theRequest;
}
//正则去除某个字符
const remove = (str) => {
	const regex = new RegExp('/', 'gi');
	if (str.length > 0) {
		str = str.replace(regex, '');
	}
	return str;
}
// 数据分层
const sortData = (oArr, length) => {
	let arr = [];
	let minArr = [];
	oArr.forEach(c => {
		if (minArr.length === length) {
			minArr = [];
		}
		if (minArr.length === 0) {
			arr.push(minArr);
		}
		minArr.push(c);
	});
	return arr;
}
//时间戳转时间
const add0 = (m) => {
	return m<10?'0'+m:m 
}
const format = (shijianchuo, type) =>{
	//shijianchuo是整数，否则要parseInt转换
	var time = (new Date(shijianchuo*1000));
	console.log(time)
	var y = time.getFullYear();
	var m = time.getMonth()+1;
	var d = time.getDate();
	var h = time.getHours();
	var mm = time.getMinutes();
	var s = time.getSeconds();
	if(type == "date"){
		return y+'-'+add0(m)+'-'+add0(d);
	}else if(type == "time"){
		return add0(h)+':'+add0(mm)+':'+add0(s);
	}else if(type == "datetime"){
		return y+'-'+add0(m)+'-'+add0(d)+' '+add0(h)+':'+add0(mm);
	}else{
		return y+'-'+add0(m)+'-'+add0(d)+' '+add0(h)+':'+add0(mm)+':'+add0(s);
	}
}
//倒计时
const countDown = (t)=> {
	var h = Math.floor(t/60/60%24);
	var m = Math.floor(t/60%60);
	var s = Math.floor(t%60);
	      
	//把时间的数字转成字符串， 如果分秒毫秒不足10， 则前面补0
	var timeStr = (h<10?"0"+h:h) +":"+ (m<10?"0"+m:m) +":"+ (s<10?"0"+s:s);
	return timeStr;
}
//判断某个时间是否在两个时间段内
const isDuringDate = (beginDateStr, endDateStr)=> {
	var curDate = new Date(),
		beginDate = new Date(beginDateStr),
		endDate = new Date(endDateStr);
	if (curDate >= beginDate && curDate <= endDate) {
		return true;
	}
	return false;
}

const pay = (res, type) => {
	if (type == 'alipay') {
		uni.requestPayment({
			provider: type,
			orderInfo: res.data.info,
			// timeStamp: res.data.
			success: res => {
				msg('支付成功')
				setTimeout(() => {
					uni.reLaunch({
						url: '/pages/orders/Index'
					})
				}, 1000)
			},
			fail(err) {
				msg('支付失败')
			}
		})
	} else {
		let info = JSON.parse(res.data.info)
		console.log(info)
		uni.requestPayment({
			provider: type,
			orderInfo: info,
			success: res => {
				msg('支付成功')
				setTimeout(() => {
					uni.reLaunch({
						url: '/pages/orders/Index'
					})
				}, 1000)
			},
			fail(err) {
				console.log(err)
				msg('支付失败')
			}
		})
	}
}
export default {
	msg,
	getQueryVariable,
	objParseParam,
	getInfoAsync,
	random,
	getRequestParameters,
	remove,
	sortData,
	copy,
	upload,
	openLocation,
	format,
	countDown,
	isDuringDate,
	pay
}
